package com.yybray.stream;

import java.util.function.Function;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * Created by Bray.ye on 2017/05/24 15:49.
 */
public class ParallelStreams {

    /**
     * 顺序流归约
     * @param l
     * @return
     */
    public static long sequentialSum(long l) {
        //iterate生成封装类 可能让程序整体性能更差
        return Stream.iterate(1l, n -> ++n).sequential().limit(l).reduce(0l, Long::sum);
    }

    /**
     * 并行流归约
     * @param l
     * @return
     */
    public static long parallelSum(long l) {
        return Stream.iterate(1l, n -> ++n).parallel().limit(l).reduce(0l, Long::sum);
    }

    /**
     * 顺序流归约
     * @param l
     * @return
     */
    public static long sequentialRangedSum(long l) {
        //LongStream.rangeClosed直接产生原始类型的long数字，没有装箱拆箱的开销
        return LongStream.rangeClosed(1, l).sequential().reduce(0, Long::sum);
    }

    /**
     * 并行流归约
     * @param l
     * @return
     */
    public static long parallelRangedSum(long l) {
        return LongStream.rangeClosed(1, l).parallel().reduce(0, Long::sum);
    }

    /**
     * 普通迭代
     * @param l
     * @return
     */
    public static long iterativeSum(long l) {
        long i = 0;
        for (int j = 0; j < l; j++) {
            i += j;
        }
        return i;
    }

}
